/**
 * Created by Merdan on 2017/2/13.
 */
adminApp
    .service('$menuItems', function() {
        this.menuItems = [];
        var $menuItemsRef = this;
        var menuItemObj = {
            parent: null,

            title: '',
            link: '', // starting with "./" will refer to parent link concatenation
            state: '', // will be generated from link automatically where "/" (forward slashes) are replaced with "."
            icon: '',
            isActive: false,
            label: null,
            menuItems: [],
            setLabel: function(label, color, hideWhenCollapsed)
            {
                if(typeof hideWhenCollapsed === 'undefined')
                    hideWhenCollapsed = true;

                this.label = {
                    text: label,
                    classname: color,
                    collapsedHide: hideWhenCollapsed
                };

                return this;
            },
            addItem: function(title, link, icon)
            {
                var parent = this,
                    item = angular.extend(angular.copy(menuItemObj), {
                        parent: parent,
                        title: title,
                        link: link,
                        icon: icon
                    });

                if(item.link)
                {
                    if(item.link.match(/^\./))
                        item.link = parent.link + item.link.substring(1, link.length);

                    if(item.link.match(/^-/))
                        item.link = parent.link + '-' + item.link.substring(2, link.length);

                    item.state = $menuItemsRef.toStatePath(item.link);
                }

                this.menuItems.push(item);

                return item;
            }
        };

        this.addItem = function(title, link, icon, type)
        {
            type = type === undefined ? false : type;
            var item = angular.extend(angular.copy(menuItemObj), {
                title: title,
                link: link,
                state: this.toStatePath(link),
                icon: icon,
                type:type
            });
            console.log('item.type', item.type);
            this.menuItems.push(item);

            return item;
        };

        this.addHeader = function (title) {
            var item = angular.extend(angular.copy(menuItemObj), {
                title: title,
                isHeader: true
            });
            this.menuItems.push(item);
            return item;
        };

        this.getAll = function()
        {
            return this.menuItems;
        };

        this.prepareSidebarMenu = function()
        {
            this.addHeader('菜单');
            var blog	= this.addItem('用户管理', 			'/users', 			'glyphicon glyphicon-user');
            var canteen = this.addItem('餐厅管理', 			'/canteens', 		'glyphicon glyphicon-modal-window');
            var sku		= this.addItem('物料管理', 			'/product', 		'glyphicon glyphicon-barcode');

            sku.addItem('物料列表', 	'/product');
            sku.addItem('物料分类', 	'./category');
            // dashboard.addItem('Update Hightlights', '/app/update-highlights').setLabel('v1.3', 'pink');
            return this;
        };

        this.instantiate = function()
        {
            return angular.copy( this );
        };

        this.toStatePath = function(path)
        {
            return path.replace(/\//g, '.').replace(/^\./, '');
        };

        this.setActive = function(path)
        {
            this.iterateCheck(this.menuItems, this.toStatePath(path));
        };

        this.setActiveParent = function(item)
        {
            item.isActive = true;
            item.isOpen = true;

            if(item.parent)
                this.setActiveParent(item.parent);
        };

        this.iterateCheck = function(menuItems, currentState)
        {
            angular.forEach(menuItems, function(item)
            {
                if(item.state === currentState)
                {
                    item.isActive = true;
                    if(item.parent != null)
                        $menuItemsRef.setActiveParent(item.parent);
                    if(item.menuItems.length)
                    {
                        $menuItemsRef.iterateCheck(item.menuItems, currentState);
                    }
                }
                else
                {
                    item.isActive = false;
                    item.isOpen = false;

                    if(item.menuItems.length)
                    {
                        $menuItemsRef.iterateCheck(item.menuItems, currentState);
                    }
                }
            });
        }
    })
    .factory('errorInterceptor', ['$q', '$rootScope', '$location', 'SweetAlert', '$timeout',
        function ($q, $rootScope, $location, SweetAlert, $timeout) {
            return {
                responseError: function (response) {
                    if (response && response.status === 401) {
                        SweetAlert.swal('', lang.ask_login, "error");
                        $timeout(function (){
                            //location.href = 'dashboard/login';
                        }, 1000);
                        return response;
                    }
                    if (response && response.status === 403) {
                        SweetAlert.swal('', lang.ask_login, "warning");
                        $timeout(function (){
                            //location.href = 'dashboard/login';
                        }, 1000);
                        return response;
                    }
                    if (response && response.status === 404) {
                        SweetAlert.swal('', lang.not_found, "error");
                        return response;
                    }
                    if (response && response.status >= 500) {
                        SweetAlert.swal('', lang.unknown, "error");
                        return response;
                    }
                    return $q.reject(response);
                }
            };
        }])
    .factory('User', ['$resource',  'DASHBOARD_API',
        function ($resource,  DASHBOARD_API) {
            return $resource(DASHBOARD_API + '/user/:id', {}, {
                'get': {method: 'GET'},
                'save': {method: 'POST'},
                'show': {method: 'GET', params: {id: '@id'}},
                'update': {method: 'PUT', params: {id: '@id'}}
            });
        }
    ])
    .factory('Canteen', ['$resource',  'DASHBOARD_API',
        function ($resource,  DASHBOARD_API) {
            return $resource(DASHBOARD_API + '/canteen/:id', {}, {
                'get': {method: 'GET'},
                'save': {method: 'POST'},
                'show': {method: 'GET', params: {id: '@id'}},
                'update': {method: 'PUT', params: {id: '@id'}}
            });
        }
    ])
    .factory('Product', ['$resource',  'DASHBOARD_API',
        function ($resource,  DASHBOARD_API) {
            return $resource(DASHBOARD_API + '/product/:id', {}, {
                'get': {method: 'GET'},
                'save': {method: 'POST'},
                'show': {method: 'GET', params: {id: '@id'}},
                'update': {method: 'PUT', params: {id: '@id'}}
            });
        }
    ])
    .factory('Category', ['$resource',  'DASHBOARD_API',
        function ($resource,  DASHBOARD_API) {
            return $resource(DASHBOARD_API + '/category/:id', {}, {
                'get': {method: 'GET'},
                'save': {method: 'POST'},
                'show': {method: 'GET', params: {id: '@id'}},
                'update': {method: 'PUT', params: {id: '@id'}}
            });
        }
    ])
    .factory('Sku', ['$resource',  'DASHBOARD_API',
        function ($resource,  DASHBOARD_API) {
            return $resource(DASHBOARD_API + '/sku/:id', {}, {
                'get': {method: 'GET'},
                'save': {method: 'POST'},
                'show': {method: 'GET', params: {id: '@id'}},
                'update': {method: 'PUT', params: {id: '@id'}}
            });
        }
    ])
    .factory('Record', ['$resource',  'DASHBOARD_API',
        function ($resource,  DASHBOARD_API) {
            return $resource(DASHBOARD_API + '/record/:id', {}, {
                'get': {method: 'GET'},
                'save': {method: 'POST'},
                'show': {method: 'GET', params: {id: '@id'}},
                'update': {method: 'PUT', params: {id: '@id'}}
            });
        }
    ])
    .factory('TeamMember', ['$resource',  'DASHBOARD_API',
        function ($resource,  DASHBOARD_API) {
            return $resource(DASHBOARD_API + '/teamMembers/:id', {}, {
                'get': {method: 'GET'},
                'save': {method: 'POST'},
                'show': {method: 'GET', params: {id: '@id'}},
                'update': {method: 'PUT', params: {id: '@id'}}
            });
        }
    ])
    .factory('Client', ['$resource',  'DASHBOARD_API',
        function ($resource,  DASHBOARD_API) {
            return $resource(DASHBOARD_API + '/clients/:id', {}, {
                'get': {method: 'GET'},
                'save': {method: 'POST'},
                'show': {method: 'GET', params: {id: '@id'}},
                'update': {method: 'PUT', params: {id: '@id'}}
            });
        }
    ])
    .factory('Option', ['$resource',  'DASHBOARD_API',
        function ($resource,  DASHBOARD_API) {
            return $resource(DASHBOARD_API + '/options/:params', {}, {
                'get': {method: 'GET'},
                'save': {method: 'POST'},
                'techList': {method: 'GET', params: {params: 'tech-list'}}
            });
        }
    ]);